package com.gjy.zk.config;

import lombok.Data;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-09-29 17:59:30
 */
@Configuration
@ConfigurationProperties(prefix = "zookeeper")
@Data
public class ZookeeperConfig {

    private String connectString;
    private int sessionTimeout = 60000;
    private int connectionTimeout = 15000;
    private int baseSleepTime = 1000;
    private int maxRetries = 3;
    private String namespace;

    /**
     * 创建CuratorFramework客户端
     */
    @Bean
    public CuratorFramework curatorFramework() {
        // 重试策略：基础休眠时间1000ms，最大重试次数3次
        ExponentialBackoffRetry retry = new ExponentialBackoffRetry(baseSleepTime, maxRetries);

        // 构建CuratorFramework
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(connectString)
                .sessionTimeoutMs(sessionTimeout)
                .connectionTimeoutMs(connectionTimeout)
                .retryPolicy(retry)
                .namespace(namespace)
                .build();

        // 启动客户端
        client.start();

        return client;
    }

}
